var CaseAddInfoDlg = {caseAddInfoData: {}, zTreeInstance: null, validateFields: {}};//初始化病例上传详情对话框
//清除数据
CaseAddInfoDlg.clearData = function () {
    this.caseAddInfoData = {};
};
//设置对话框中的数据 @param key 数据的名称 @param val 数据的具体值
CaseAddInfoDlg.set = function (key, val) {
    this.caseAddInfoData[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
    return this;
};
//设置对话框中的数据 @param key 数据的名称 @param val 数据的具体值
CaseAddInfoDlg.get = function (key) {
    return $("#" + key).val();
};
//关闭此对话框
CaseAddInfoDlg.close = function () {
    parent.layer.close(parent.layer.getFrameIndex(window.name));
};
//收集数据
CaseAddInfoDlg.collectData = function () {
    this.set('id').set('personacct').set('szm').set('phone').set('nationality').set('nation').set('customerName').set('customerPhone').set('idCard').set('customerAge').set('birthday').set('insuranceState').set('saveStatus').set('selectionStatus').set('customerSex').set('medicalInsurance').set('applyOutpatient')
        .set('occupation').set('flag').set('createTime').set('updateTime').set('applyTime').set('address').set('personCondition').set('maritalStatus').set('medicalDepartment').set('medicalType').set('person_weight').set('personHeight').set('patientComplaints').set('presentIllness')
        .set('pastHistory').set('systemicDiseases').set('diagnosis').set('physicalExam').set('num').set('leftUp').set('rightUp').set('leftDown').set('rightDown')
        .set('treatmentAdvice').set('designThink').set('description').set('remarks').set('mark').set('treatmentSteps').set('personWeight')
        .set('code').set('caseType').set('hospitalizedTime').set('BMI').set('suppleExamResult').set('caseComment');
    //治疗步骤
    var treatmentSteps = [];
    $(".treatmentSteps").each(function () {
        treatmentSteps.push($(this).val()); //这里的value就是每一个input的value值~
    });
    this.caseAddInfoData['treatmentSteps'] = treatmentSteps.join("&&");//把一组检查的所有左上数组通过&&分割拼接成字符串 比如  1&&1
    var ratingItemsScoreList = [];
    $(".ratingItemsScore").each(function () {
        ratingItemsScoreList.push($(this).val()); //这里的value就是每一个input的value值~
    });
    this.caseAddInfoData['ratingItemsScore'] = ratingItemsScoreList.join("&&");//把一组检查的所有左上数组通过&&分割拼接成字符串 比如  1&&1
    var ratingItemsList = [];
    $(".ratingItems").each(function () {
        ratingItemsList.push($(this).val()); //这里的value就是每一个input的value值~
    });
    this.caseAddInfoData['ratingItems'] = ratingItemsList.join("&&");//把一组检查的所有左上数组通过&&分割拼接成字符串 比如  1&&1
};
//验证数据是否为空
CaseAddInfoDlg.validate = function () {
    $('#caseAddInfoForm').data("bootstrapValidator").resetForm();
    $('#caseAddInfoForm').bootstrapValidator('validate');
    return $("#caseAddInfoForm").data('bootstrapValidator').isValid();
};
//初始化数据
CaseAddInfoDlg.initData = function () {
    var seletecustomerSex = $('#customerSexValue').val();
    var seletemaritalStatus = $('#maritalStatusValue').val();
    var seletenationality = $('#nationalityValue').val();
    var seleteinsuranceState = $('#insuranceStateValue').val();
    var seletemedicalType = $('#medicalTypeValue').val();
    if (seletecustomerSex != "") {
        $("#customerSex option[value='" + seletecustomerSex + "']").attr("selected", "selected");
    }
    if (seletemaritalStatus != "") {
        $("#maritalStatus option[value='" + seletemaritalStatus + "']").attr("selected", "selected");
    }
    if (seletenationality != "") {
        $("#nationality option[value='" + seletenationality + "']").attr("selected", "selected");
    }
    if (seleteinsuranceState != "") {
        $("#insuranceState option[value='" + seleteinsuranceState + "']").attr("selected", "selected");
    }
    if (seletemedicalType != "") {
        $("#medicalType option[value='" + seletemedicalType + "']").attr("selected", "selected");
    }
};

var avatarUp, avatarUp1, avatarUp2, avatarUp3, avatarUp4, avatarUp5, avatarUp6, avatarUp7, avatarUp8, avatarUp9 = "";
function iconTypeChange() {
    avatarUp = new $IconUpload("avatar");
    avatarUp.initIcon();
    avatarUp1 = new $IconUpload("avatar1");
    avatarUp1.initIcon();
    avatarUp2 = new $IconUpload("avatar2");
    avatarUp2.initIcon();
    avatarUp3 = new $IconUpload("avatar3");
    avatarUp3.initIcon();
    avatarUp4 = new $IconUpload("avatar4");
    avatarUp4.initIcon();
    avatarUp5 = new $IconUpload("avatar5");
    avatarUp5.initIcon();
    avatarUp6 = new $IconUpload("avatar6");
    avatarUp6.initIcon();
    avatarUp7 = new $IconUpload("avatar7");
    avatarUp7.initIcon();
    avatarUp8 = new $IconUpload("avatar8");
    avatarUp8.initIcon();
    avatarUp9 = new $IconUpload("avatar9");
    avatarUp9.initIcon();
}

var imagePathText = '';
var imagePathId = '';
$(function () {
    $(".showDetails").click(function () {
        $(this).parent().siblings().toggle();
        $(this).children().toggle();
    });
    subsequent = function (id) {
        var index = layer.open({
            type: 2,
            title: '复诊预约',
            area: ['70%', '95%'], //宽高
            fix: true, //不固定
            maxmin: true,
            content: Feng.ctxPath + '/doctorLooked/subsequent_info/' + id + '/2',
        });
        this.layerIndex = index;
    };
    $(document).on('click', '.imagePath', function () {
        var _this = $(this);//将当前的pimg元素作为_this传入函数
        imgShow("#outerdiv", "#innerdiv", "#bigimg", _this);
    });

    iconTypeChange();

    function imgShow(outerdiv, innerdiv, bigimg, _this) {
        var src = _this.attr("src");//获取当前点击的pimg元素中的src属性
        imagePathId = _this.parent().attr("id")
        imagePathText = _this.siblings('span').text()
        $(bigimg).attr("src", src);//设置#bigimg元素的src属性
        if (imagePathText === "术前") {
            $("#innerdiv").find('.dashed-box,.shuzhong,.shuhou').hide();
            $("#innerdiv").find('.shuqian').show();
        } else if (imagePathText === "术中") {
            $("#innerdiv").find('.dashed-box,.shuqian,.shuhou').hide();
            $("#innerdiv").find('.shuzhong').show();
        } else if (imagePathText === "术后") {
            $("#innerdiv").find('.dashed-box,.shuqian,.shuzhong').hide();
            $("#innerdiv").find('.shuhou').show();
        } else {
            $("#innerdiv").find('.questionBox').hide();
        }
        $("<img/>").attr("src", src).load(function () {/*获取当前点击图片的真实大小，并显示弹出层及大图*/
            var windowW = $(window).width();//获取当前窗口宽度
            var windowH = $(window).height();//获取当前窗口高度
            var realWidth = this.width;//获取图片真实宽度
            var realHeight = this.height;//获取图片真实高度
            var imgWidth, imgHeight;
            var scale = 0.8;//缩放尺寸，当图片真实宽度和高度大于窗口宽度和高度时进行缩放
            if (realHeight > windowH * scale) {//判断图片高度
                imgHeight = windowH * scale;//如大于窗口高度，图片高度进行缩放
                imgWidth = imgHeight / realHeight * realWidth;//等比例缩放宽度
                if (imgWidth > windowW * scale) {//如宽度扔大于窗口宽度
                    imgWidth = windowW * scale;//再对宽度进行缩放
                }
            } else if (realWidth > windowW * scale) {//如图片高度合适，判断图片宽度
                imgWidth = windowW * scale;//如大于窗口宽度，图片宽度进行缩放
                imgHeight = imgWidth / realWidth * realHeight;//等比例缩放高度
            } else {//如果图片真实高度和宽度都符合要求，高宽不变
                imgWidth = realWidth;
                imgHeight = realHeight;
            }
            $(bigimg).css("width", imgWidth);//以最终的宽度对图片缩放
            var w = (windowW - imgWidth) / 2;//计算图片与窗口左边距
            var h = (windowH - imgHeight) / 2;//计算图片与窗口上边距
            $(innerdiv).css({"top": h, "left": w});//设置#innerdiv的top和left属性
            $(outerdiv).fadeIn("fast");//淡入显示#outerdiv及.pimg
        });
        //再次点击淡出消失弹出层
        $(outerdiv).click(function (e) {
            $(this).fadeOut("fast");
        });// $("#innerdiv").find('.questionBox,.dashed-box').remove();
    }
});

window.onload = function () {
    function stopDefault(e) {
        if (e && e.preventDefault) e.preventDefault(); else window.event.returnValue = false;
        return false;
    }

    $("#innerdiv").click(function (e) {
        e.stopPropagation();
    });

    function oBox() {
        var wId = "w";
        var index = 0;
        var target = null;
        var startX = 0, startY = 0;
        var dragging = false;
        var startL = 0, startT = 0, boxHeight = 0, boxWidth = 0;
        var boxObj = document.getElementById("innerdiv");
        var newMarkPos = {
            "left": startL,////按下时鼠标距离的左边的距离
            "top": startT////按下时鼠标距离的上边的距离
        };

        boxObj.onmousedown = function (e) {//鼠标点击
            dragging = true;
            var e = window.event || e;//e.pageY，e.pageX兼容
            target = e.target || e.srcElement; //获取document 对象的引用
            if (target.src) {
                stopDefault(e)
            }
            var frame = $("#innerdiv");
            var referenceSize = {"pos": frame.offset(), "width": frame.outerWidth(), "height": frame.outerHeight()};
            var scrollTop = boxObj.scrollTop;
            var scrollLeft = boxObj.scrollLeft;
            var ePageX = e.clientX + scrollLeft;
            var ePageY = e.clientY + scrollTop;
            startX = ePageX;//按下时鼠标距离页面的距离
            startY = ePageY;
            startL = startX - referenceSize.pos.left;//按下时鼠标距离的左边和上边的距离
            startT = startY - referenceSize.pos.top;
            index++;
            if (target.className.match(/del-box/i)) {// 如果鼠标在 box 上被按下
                dragging = false;// 允许拖动
                var movingBox = document.getElementById("moving_box");// 设置当前 box 的 id 为 moving_box
                if (movingBox !== null) {
                    movingBox.removeAttribute("id");
                }
                target.id = "moving_box";
                removeBox(target);
            } else {
                if (imagePathText === "术前") {
                    $("#innerdiv").find('.dashed-box,.shuqian').remove();
                } else if (imagePathText === "术中") {
                    $("#innerdiv").find('.dashed-box,.shuzhong').remove();
                } else if (imagePathText === "术后") {
                    $("#innerdiv").find('.dashed-box,.shuhou').remove();
                } else {
                    $("#innerdiv").find('.dashed-box,.qita').remove();
                }
                var div = document.createElement("div");
                div.id = wId + index;
                div.className = "dashed-box";
                boxObj.appendChild(div);
                div = null;
            }
        };

        boxObj.onmouseup = function (e) {//鼠标离开
            var e = window.event || e;
            if (boxWidth >= 5 || boxHeight >= 5) {
                boxObj.removeChild(dragBox(wId + index));
                index++;
                var div = document.createElement("div");
                var spanObj = document.createElement("span");
                var spanObjTow = document.createElement("span");
                spanObj.className = 'del-box';
                spanObj.innerHTML = parseInt(newMarkPos.left) + "," + parseInt(newMarkPos.top);
                spanObjTow.className = 'delBoxTow';
                spanObjTow.innerHTML = parseInt(newMarkPos.left + boxWidth) + "," + parseInt(newMarkPos.top + boxHeight);
                var initialCoordinate = parseInt(newMarkPos.left) + "," + parseInt(newMarkPos.top);
                var endpointCoordinate = parseInt(newMarkPos.left + boxWidth) + "," + parseInt(newMarkPos.top + boxHeight);
                div.appendChild(spanObj);
                div.appendChild(spanObjTow);
                if (imagePathText === "术前") {
                    div.className = "questionBox questionBorder shuqian";
                } else if (imagePathText === "术中") {
                    div.className = "questionBox questionBorder shuzhong";
                } else if (imagePathText === "术后") {
                    div.className = "questionBox questionBorder shuhou";
                } else {
                    div.className = "questionBox questionBorder qita";
                }
                div.style.left = newMarkPos.left + "px";
                div.style.top = newMarkPos.top + "px";
                div.style.width = boxWidth + "px";
                div.style.height = boxHeight + "px";
                boxObj.appendChild(div);
                div = null;
                boxWidth = 0;
                boxHeight = 0;
                if (imagePathText === "术前") {
                    $("#imagePathPreoperative").val(imagePathId + ";" + imagePathText + ";" + initialCoordinate + ";" + endpointCoordinate)
                }
                if (imagePathText === "术中") {
                    $("#imagePathIntraoperative").val(imagePathId + ";" + imagePathText + ";" + initialCoordinate + ";" + endpointCoordinate)
                }
                if (imagePathText === "术后") {
                    $("#imagePathPostoperative").val(imagePathId + ";" + imagePathText + ";" + initialCoordinate + ";" + endpointCoordinate)
                }
            } else {
                if (dragging) {
                    boxObj.removeChild(dragBox(wId + index));
                }
            }
            dragging = false;
        };

        boxObj.onmousemove = function (e) {//鼠标移动
            var e = window.event || e;
            stopDefault(e);
            if (dragging) {
                var scrollTop = boxObj.scrollTop;
                var scrollLeft = boxObj.scrollLeft;
                var ePX = e.clientX + scrollLeft;
                var ePY = e.clientY + scrollTop;
                var disW = ePX - startX;
                var disH = ePY - startY;
                var L = startL + disW;
                var T = startT + disH;
                if (disW > 0) {
                    if (L >= 0) {
                        boxWidth = disW
                    }
                    newMarkPos.left = startL;
                } else {
                    if (L <= 0) {
                        L = 0;
                        boxWidth = startL;
                    }
                    boxWidth = (startL - L);
                    newMarkPos.left = L;
                }
                if (disH > 0) {
                    if (T >= 0) {
                        boxHeight = disH
                    }
                    newMarkPos.top = startT;
                } else {
                    if (T <= 0) {
                        T = 0;
                        boxHeight = startT;
                    }
                    boxHeight = (startT - T);
                    newMarkPos.top = T;
                }
                dragBox(wId + index).style.left = newMarkPos.left + "px";
                dragBox(wId + index).style.top = newMarkPos.top + "px";
                dragBox(wId + index).style.width = Math.abs(boxWidth) + "px";
                dragBox(wId + index).style.height = Math.abs(boxHeight) + "px";
                stopDefault(e)
            }
        };
        var dragBox = function (id) {
            return document.getElementById(id);
        }
    }
    oBox();
    function removeBox(obj) {
        if (obj) {
            var innerdiv = document.getElementById('innerdiv');
            if (obj.className == 'del-box') {
                var objId = document.getElementById(obj.id);
                innerdiv.removeChild(objId.parentNode);
            }
        }
    }
};

var tips;
$(document).click(function () {
    layer.close(tips);
});